package com.oocl.chat.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.oocl.chat.dao.UserOperate;
import com.oocl.chat.db.DBUtil;
import com.oocl.chat.pojo.Message;

public class UserOperateImpl implements UserOperate {
	//  返回1代表插入成功，返回0代表插入失败
	public int addUser(Message message) {
		String sql = "insert into users(id,name,password,status) values(seq03.nextval,?,?,?)";
		Connection con=null;
		PreparedStatement pst = null;
		int m = 0;
		String[] info = message.getContent().split(",");
		int verify = findUser(info[0]);
		if(verify==0){
			return 0;
		}
		try {
			con=DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, info[0]);
			pst.setString(2, info[1]);
			pst.setBoolean(3, false);
			m = pst.executeUpdate();
		} catch (SQLException e) {
			return 0;
		} finally {
			DBUtil.close(con, pst, null);
		}
		return m;
	}
	//返回1代表没有同名用户，返回0代表存在同名用户,
	private int findUser(String name) {
		String sql = "select * from users where name=?";
		Connection con=null;
		PreparedStatement pst = null;
		ResultSet rs =null;
		try {
			con=DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			rs = pst.executeQuery();
			if (rs.next()) {
				return 0;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(null, pst, rs);
		}
		return 1;
	}
	public int findUserByPassName(String name,String password){
		String sql = "select * from users where name=? and password=?";
		Connection con=null;
		PreparedStatement pst = null;
		ResultSet rs =null;
		try {
			con=DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			pst.setString(2, password);
			rs = pst.executeQuery();
			if (rs.next()) {
				return 1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(null, pst, rs);
		}
		return 0;
	}

}
